Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [93]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [94]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[94]:
<matplotlib.image.AxesImage at 0x7fc139f1f748>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [95]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[95]:
<matplotlib.image.AxesImage at 0x7fc139ef8c88>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [96]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[96]:
<matplotlib.image.AxesImage at 0x7fc139e4e8d0>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [97]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[97]:
<matplotlib.image.AxesImage at 0x7fc139e28c88>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [98]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!

    
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections

# Extract the pre-trained eye detector from an xml file
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

# Extract the face area in gray 
# gray_face = gray[y:y+h, x:x+w]
# Plot the image with both faces and eyes detected
# fig = plt.figure(figsize = (6,6))
# ax1 = fig.add_subplot(111)
# ax1.set_xticks([])
# ax1.set_yticks([])
# ax1.set_title('Gray face')
# ax1.imshow(gray_face)

# Detect the eyes in image
eyes = eye_cascade.detectMultiScale(gray, 1.1, 3)

# Print the number of faces detected in the image
print('Number of eyes detected:', len(eyes))

# Get the bounding box for each detected face
for (x,y,w,h) in eyes:
    # Add a green bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (0,255,0), 3)



# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Number of eyes detected: 2
Out[98]:
<matplotlib.image.AxesImage at 0x7fc139d80d68>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [99]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
In [100]:
# Call the laptop camera face/eye detector function above
# laptop_camera_go()

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [101]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[101]:
<matplotlib.image.AxesImage at 0x7fc13b201278>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [102]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 12
Out[102]:
<matplotlib.image.AxesImage at 0x7fc13b0956a0>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [103]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!

denoised_image = np.copy(image_with_noise)
denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise,None,25,25,7,7)

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Denoised Image')
ax1.imshow(denoised_image)
Out[103]:
<matplotlib.image.AxesImage at 0x7fc13b0d4780>
In [104]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result

# Convert the RGB  image to grayscale
gray_denoised = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_denoised, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(denoised_image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Denoised Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[104]:
<matplotlib.image.AxesImage at 0x7fc13b85c208>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [105]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[105]:
<matplotlib.image.AxesImage at 0x7fc0ab8f0c88>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [106]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
kernel_blur = np.ones((4,4),np.float32)/16
# Apply the blur kernal
gray_blurred = cv2.filter2D(gray,-1,kernel_blur)

## TODO: Then perform Canny edge detection and display the output

# Perform Canny edge detection
edges = cv2.Canny(gray_blurred,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges after blurring')
ax2.imshow(edges, cmap='gray')
Out[106]:
<matplotlib.image.AxesImage at 0x7fc13a767a20>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [107]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[107]:
<matplotlib.image.AxesImage at 0x7fc0ab905208>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [108]:
## TODO: Implement face detection

# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

## TODO: Blur the bounding box around each detected face using an averaging filter and display the result

# Blur for each detected face
blur_level = 80
kernel_blur = np.ones((blur_level,blur_level),np.float32)/(blur_level*blur_level)
for (x,y,w,h) in faces:
    # Select the face area
    face = image_with_detections[y:y+h, x:x+w]
    # Blur the face 
    face_blurred = cv2.filter2D(face,-1,kernel_blur)
    # Put the blurred face back to the image
    image_with_detections[y:y+h, x:x+w] = face_blurred
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with blurred face')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[108]:
<matplotlib.image.AxesImage at 0x7fc0fe88eeb8>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [109]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [110]:
# Run laptop identity hider
#laptop_camera_go()

Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [111]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [112]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [234]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
from keras import regularizers


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

model = Sequential()
model.add(Conv2D(filters=8, kernel_size=2, padding='same', activation='relu', input_shape=(96,96,1)))
model.add(MaxPooling2D(pool_size=2))
# model.add(Dropout(0.1))
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', kernel_regularizer=regularizers.l1(0.01)))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.1))
# model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', kernel_regularizer=regularizers.l1(0.01)))
# model.add(MaxPooling2D(pool_size=2))
# model.add(Dropout(0.3))
# model.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu', kernel_regularizer=regularizers.l1(0.01)))
# model.add(MaxPooling2D(pool_size=2))
# model.add(Dropout(0.3))
# model.add(Conv2D(filters=256, kernel_size=2, padding='same', activation='relu', kernel_regularizer=regularizers.l1(0.01)))
# model.add(MaxPooling2D(pool_size=2))
# model.add(Dropout(0.3))
# model.add(Dense(500, activation='relu', kernel_regularizer=regularizers.l1(0.01)))
model.add(Flatten())
# model.add(Dropout(0.4))
# model.add(Dense(500, activation='relu', kernel_regularizer=regularizers.l1(0.01)))
model.add(Dense(30))



# Summarize the model
model_config = model.get_config()
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_25 (Conv2D)           (None, 96, 96, 8)         40        
_________________________________________________________________
max_pooling2d_18 (MaxPooling (None, 48, 48, 8)         0         
_________________________________________________________________
conv2d_26 (Conv2D)           (None, 48, 48, 16)        528       
_________________________________________________________________
max_pooling2d_19 (MaxPooling (None, 24, 24, 16)        0         
_________________________________________________________________
dropout_15 (Dropout)         (None, 24, 24, 16)        0         
_________________________________________________________________
flatten_13 (Flatten)         (None, 9216)              0         
_________________________________________________________________
dense_15 (Dense)             (None, 30)                276510    
=================================================================
Total params: 277,078
Trainable params: 277,078
Non-trainable params: 0
_________________________________________________________________

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Your model is required to attain a validation loss (measured as mean squared error) of at least XYZ. When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [235]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam
from keras.callbacks import ModelCheckpoint
from keras.callbacks import EarlyStopping
from keras.callbacks import ReduceLROnPlateau

## TODO: Compile the model
model.compile(optimizer='RMSprop', loss='mean_squared_error', metrics=['accuracy'])

## TODO: Train the model
epochs = 25
checkpointer = ModelCheckpoint(filepath='weights.best.from_RMSprop', 
                               verbose=1, save_best_only=True)
earlystopper = EarlyStopping(patience=50)
reduce_lr = ReduceLROnPlateau()
history = model.fit(X_train, y_train,
          epochs=epochs, batch_size=10, validation_split=0.1, callbacks=[checkpointer, reduce_lr, earlystopper], verbose=1)

## TODO: Save the model as model.h5
model.save('my_model.h5')
Train on 1926 samples, validate on 214 samples
Epoch 1/25
1900/1926 [============================>.] - ETA: 0s - loss: 0.3572 - acc: 0.6005Epoch 00000: val_loss improved from inf to 0.09351, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 2s - loss: 0.3537 - acc: 0.6033 - val_loss: 0.0935 - val_acc: 0.6636
Epoch 2/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0335 - acc: 0.7096Epoch 00001: val_loss improved from 0.09351 to 0.01687, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0329 - acc: 0.7103 - val_loss: 0.0169 - val_acc: 0.6589
Epoch 3/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0116 - acc: 0.7070Epoch 00002: val_loss improved from 0.01687 to 0.00937, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0115 - acc: 0.7098 - val_loss: 0.0094 - val_acc: 0.6589
Epoch 4/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0086 - acc: 0.7134Epoch 00003: val_loss improved from 0.00937 to 0.00742, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0086 - acc: 0.7108 - val_loss: 0.0074 - val_acc: 0.6589
Epoch 5/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0074 - acc: 0.7107Epoch 00004: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0074 - acc: 0.7103 - val_loss: 0.0083 - val_acc: 0.6589
Epoch 6/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0073 - acc: 0.7107Epoch 00005: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0073 - acc: 0.7103 - val_loss: 0.0078 - val_acc: 0.6589
Epoch 7/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0073 - acc: 0.7107Epoch 00006: val_loss improved from 0.00742 to 0.00726, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0073 - acc: 0.7103 - val_loss: 0.0073 - val_acc: 0.6589
Epoch 8/25
1900/1926 [============================>.] - ETA: 0s - loss: 0.0073 - acc: 0.7100Epoch 00007: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0073 - acc: 0.7103 - val_loss: 0.0073 - val_acc: 0.6589
Epoch 9/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7091Epoch 00008: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0073 - val_acc: 0.6589
Epoch 10/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7070Epoch 00009: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0075 - val_acc: 0.6589
Epoch 11/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7075Epoch 00010: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0082 - val_acc: 0.6589
Epoch 12/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7112Epoch 00011: val_loss improved from 0.00726 to 0.00725, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0072 - val_acc: 0.6589
Epoch 13/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7091Epoch 00012: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0073 - val_acc: 0.6589
Epoch 14/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7112Epoch 00013: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0073 - val_acc: 0.6589
Epoch 15/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7053Epoch 00014: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0074 - val_acc: 0.6589
Epoch 16/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7112Epoch 00015: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0074 - val_acc: 0.6589
Epoch 17/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7118Epoch 00016: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0074 - val_acc: 0.6589
Epoch 18/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.7096Epoch 00017: val_loss did not improve
1926/1926 [==============================] - 2s - loss: 0.0072 - acc: 0.7103 - val_loss: 0.0078 - val_acc: 0.6589
Epoch 19/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7118Epoch 00018: val_loss improved from 0.00725 to 0.00491, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 20/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7070Epoch 00019: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 21/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7091Epoch 00020: val_loss improved from 0.00491 to 0.00487, saving model to weights.best.from_RMSprop
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 22/25
1920/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7109Epoch 00021: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0050 - val_acc: 0.6589
Epoch 23/25
1890/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7111Epoch 00022: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 24/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7070Epoch 00023: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 25/25
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7086Epoch 00024: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer: Step 1: I copied the CNN architecture from the previous Dog Project. It worked quite well in previous project, so I believe it is a good start here. Correct the shape of the input and output layers to fit our data.

Step 2: Dog project is a classification problem, but detecting facial keypoint is regression problem. So I have to remove the softmax activation from the output layer. And changed the loss functino to 'mean_squared_error'.

Step 3: I removed all the Dropout layers first and train with 25 epochs for simple and quick iteration.

Step 4: Although the training loss is low, the validation loss is much higher than the training loss. So I added dropout layer and regularization to tackle overfitting.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: I tested with SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam. Among all the testing results, with RMSprop, both training loss and validation loss go down together, and the loss is the lowest among the other optimizers. And finally test with the new image, modle trained with RMSprop performed the best.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [236]:
import matplotlib.pyplot as plt
## TODO: Visualize the training and validation loss of your neural network
plt.plot(history.history['acc'][5:]) # don't care the first 5 epochs, making the graph scale readable
plt.plot(history.history['val_acc'][5:])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
In [237]:
plt.plot(history.history['loss'][5:])
plt.plot(history.history['val_loss'][5:])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: Yes, I saw overfitting: the training loss is much lower than the validation. So I added one Dropout layer, and added regularization to the dense layer.

In [117]:
from keras.models import Model
In [118]:
def my_training(model_config, optimizer):
    # Train
    model = Sequential.from_config(model_config)
    model.compile(optimizer=optimizer, loss='mean_squared_error', metrics=['accuracy'])
    epochs = 30
    checkpointer = ModelCheckpoint(filepath='weights.best.from_'+optimizer, 
                                   verbose=1, save_best_only=True)
    earlystopper = EarlyStopping(patience=50)
    reduce_lr = ReduceLROnPlateau()
    history = model.fit(X_train, y_train,
              epochs=epochs, batch_size=10, validation_split=0.1, callbacks=[checkpointer, reduce_lr, earlystopper], verbose=1)
    model.save('my_model.h5.'+optimizer)
    # Plot accuracy
    plt.plot(history.history['acc'][5:]) # don't care the first 5 epochs, making the graph scale readable
    plt.plot(history.history['val_acc'][5:])
    plt.title('model accuracy -- '+optimizer)
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    # Plot loss
    plt.plot(history.history['loss'][5:])
    plt.plot(history.history['val_loss'][5:])
    plt.title('model loss -- '+optimizer)
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
In [119]:
# my_training(model_config, 'SGD')
In [253]:
my_training(model_config, 'Adagrad')
Train on 1926 samples, validate on 214 samples
Epoch 1/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.2890 - acc: 0.6481Epoch 00000: val_loss improved from inf to 0.12994, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 2s - loss: 0.2844 - acc: 0.6490 - val_loss: 0.1299 - val_acc: 0.6729
Epoch 2/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.1102 - acc: 0.6802Epoch 00001: val_loss improved from 0.12994 to 0.09691, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.1099 - acc: 0.6854 - val_loss: 0.0969 - val_acc: 0.6869
Epoch 3/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0910 - acc: 0.6781Epoch 00002: val_loss improved from 0.09691 to 0.08553, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0909 - acc: 0.6786 - val_loss: 0.0855 - val_acc: 0.6589
Epoch 4/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0811 - acc: 0.7016Epoch 00003: val_loss improved from 0.08553 to 0.07744, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0810 - acc: 0.6999 - val_loss: 0.0774 - val_acc: 0.6636
Epoch 5/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0747 - acc: 0.7016Epoch 00004: val_loss improved from 0.07744 to 0.07199, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0747 - acc: 0.6989 - val_loss: 0.0720 - val_acc: 0.6776
Epoch 6/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0702 - acc: 0.6952Epoch 00005: val_loss improved from 0.07199 to 0.06806, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0701 - acc: 0.6963 - val_loss: 0.0681 - val_acc: 0.7009
Epoch 7/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0665 - acc: 0.7032Epoch 00006: val_loss improved from 0.06806 to 0.06546, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0665 - acc: 0.7020 - val_loss: 0.0655 - val_acc: 0.7009
Epoch 8/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0631 - acc: 0.7160Epoch 00007: val_loss improved from 0.06546 to 0.06213, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0631 - acc: 0.7150 - val_loss: 0.0621 - val_acc: 0.7196
Epoch 9/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0602 - acc: 0.7257Epoch 00008: val_loss improved from 0.06213 to 0.05887, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0602 - acc: 0.7243 - val_loss: 0.0589 - val_acc: 0.7056
Epoch 10/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0576 - acc: 0.7139Epoch 00009: val_loss improved from 0.05887 to 0.05621, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0576 - acc: 0.7124 - val_loss: 0.0562 - val_acc: 0.6963
Epoch 11/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0551 - acc: 0.7123Epoch 00010: val_loss improved from 0.05621 to 0.05385, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0551 - acc: 0.7124 - val_loss: 0.0539 - val_acc: 0.6822
Epoch 12/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0527 - acc: 0.7135Epoch 00011: val_loss improved from 0.05385 to 0.05170, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0527 - acc: 0.7134 - val_loss: 0.0517 - val_acc: 0.7196
Epoch 13/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0507 - acc: 0.7043Epoch 00012: val_loss improved from 0.05170 to 0.04962, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0506 - acc: 0.7061 - val_loss: 0.0496 - val_acc: 0.6822
Epoch 14/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0487 - acc: 0.7219Epoch 00013: val_loss improved from 0.04962 to 0.04776, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0486 - acc: 0.7212 - val_loss: 0.0478 - val_acc: 0.7056
Epoch 15/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0467 - acc: 0.7161Epoch 00014: val_loss improved from 0.04776 to 0.04584, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0467 - acc: 0.7160 - val_loss: 0.0458 - val_acc: 0.7103
Epoch 16/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0448 - acc: 0.7155Epoch 00015: val_loss improved from 0.04584 to 0.04383, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0448 - acc: 0.7144 - val_loss: 0.0438 - val_acc: 0.6776
Epoch 17/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0429 - acc: 0.7294Epoch 00016: val_loss improved from 0.04383 to 0.04198, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0429 - acc: 0.7300 - val_loss: 0.0420 - val_acc: 0.6776
Epoch 18/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0411 - acc: 0.7294Epoch 00017: val_loss improved from 0.04198 to 0.04012, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0411 - acc: 0.7279 - val_loss: 0.0401 - val_acc: 0.7056
Epoch 19/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0394 - acc: 0.7214Epoch 00018: val_loss improved from 0.04012 to 0.03896, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0394 - acc: 0.7217 - val_loss: 0.0390 - val_acc: 0.6729
Epoch 20/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0381 - acc: 0.7235Epoch 00019: val_loss improved from 0.03896 to 0.03761, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0381 - acc: 0.7243 - val_loss: 0.0376 - val_acc: 0.6776
Epoch 21/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0370 - acc: 0.7251Epoch 00020: val_loss improved from 0.03761 to 0.03649, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0370 - acc: 0.7253 - val_loss: 0.0365 - val_acc: 0.6916
Epoch 22/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0360 - acc: 0.7219Epoch 00021: val_loss improved from 0.03649 to 0.03561, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0360 - acc: 0.7227 - val_loss: 0.0356 - val_acc: 0.6776
Epoch 23/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0352 - acc: 0.7321Epoch 00022: val_loss improved from 0.03561 to 0.03470, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0351 - acc: 0.7305 - val_loss: 0.0347 - val_acc: 0.7103
Epoch 24/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0342 - acc: 0.7305Epoch 00023: val_loss improved from 0.03470 to 0.03381, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0342 - acc: 0.7357 - val_loss: 0.0338 - val_acc: 0.6729
Epoch 25/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0334 - acc: 0.7246Epoch 00024: val_loss improved from 0.03381 to 0.03297, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0334 - acc: 0.7269 - val_loss: 0.0330 - val_acc: 0.6729
Epoch 26/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0325 - acc: 0.7267Epoch 00025: val_loss improved from 0.03297 to 0.03218, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0325 - acc: 0.7264 - val_loss: 0.0322 - val_acc: 0.7009
Epoch 27/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0317 - acc: 0.7278Epoch 00026: val_loss improved from 0.03218 to 0.03140, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0317 - acc: 0.7259 - val_loss: 0.0314 - val_acc: 0.6963
Epoch 28/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0309 - acc: 0.7298Epoch 00027: val_loss improved from 0.03140 to 0.03054, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0308 - acc: 0.7305 - val_loss: 0.0305 - val_acc: 0.6682
Epoch 29/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0301 - acc: 0.7374Epoch 00028: val_loss improved from 0.03054 to 0.02983, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0301 - acc: 0.7357 - val_loss: 0.0298 - val_acc: 0.7150
Epoch 30/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0294 - acc: 0.7278Epoch 00029: val_loss improved from 0.02983 to 0.02907, saving model to weights.best.from_Adagrad
1926/1926 [==============================] - 1s - loss: 0.0293 - acc: 0.7279 - val_loss: 0.0291 - val_acc: 0.6776
In [121]:
# my_training(model_config, 'Adadelta')
In [254]:
my_training(model_config, 'Adam')
Train on 1926 samples, validate on 214 samples
Epoch 1/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.3381 - acc: 0.6380Epoch 00000: val_loss improved from inf to 0.09071, saving model to weights.best.from_Adam
1926/1926 [==============================] - 2s - loss: 0.3311 - acc: 0.6397 - val_loss: 0.0907 - val_acc: 0.6636
Epoch 2/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0317 - acc: 0.7059Epoch 00001: val_loss improved from 0.09071 to 0.00801, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0311 - acc: 0.7056 - val_loss: 0.0080 - val_acc: 0.6589
Epoch 3/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0060 - acc: 0.7123Epoch 00002: val_loss improved from 0.00801 to 0.00641, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0060 - acc: 0.7108 - val_loss: 0.0064 - val_acc: 0.6589
Epoch 4/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0054 - acc: 0.7128Epoch 00003: val_loss improved from 0.00641 to 0.00561, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0054 - acc: 0.7103 - val_loss: 0.0056 - val_acc: 0.6589
Epoch 5/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0054 - acc: 0.7105Epoch 00004: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0054 - acc: 0.7108 - val_loss: 0.0057 - val_acc: 0.6589
Epoch 6/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0054 - acc: 0.7134Epoch 00005: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0054 - acc: 0.7113 - val_loss: 0.0056 - val_acc: 0.6589
Epoch 7/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0053 - acc: 0.7086Epoch 00006: val_loss improved from 0.00561 to 0.00557, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0053 - acc: 0.7103 - val_loss: 0.0056 - val_acc: 0.6589
Epoch 8/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0053 - acc: 0.7102Epoch 00007: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0053 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 9/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0053 - acc: 0.7111Epoch 00008: val_loss improved from 0.00557 to 0.00510, saving model to weights.best.from_Adam
1926/1926 [==============================] - 2s - loss: 0.0053 - acc: 0.7103 - val_loss: 0.0051 - val_acc: 0.6589
Epoch 10/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0050 - acc: 0.7107Epoch 00009: val_loss improved from 0.00510 to 0.00495, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0050 - acc: 0.7098 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 11/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7155Epoch 00010: val_loss improved from 0.00495 to 0.00458, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7129 - val_loss: 0.0046 - val_acc: 0.6636
Epoch 12/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.7203Epoch 00011: val_loss improved from 0.00458 to 0.00454, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0043 - acc: 0.7207 - val_loss: 0.0045 - val_acc: 0.6636
Epoch 13/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0042 - acc: 0.7188Epoch 00012: val_loss improved from 0.00454 to 0.00426, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0042 - acc: 0.7181 - val_loss: 0.0043 - val_acc: 0.6869
Epoch 14/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0040 - acc: 0.7203Epoch 00013: val_loss improved from 0.00426 to 0.00397, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0040 - acc: 0.7217 - val_loss: 0.0040 - val_acc: 0.6776
Epoch 15/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0039 - acc: 0.7141Epoch 00014: val_loss improved from 0.00397 to 0.00378, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0039 - acc: 0.7155 - val_loss: 0.0038 - val_acc: 0.6636
Epoch 16/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0038 - acc: 0.7198- ETA: 1sEpoch 00015: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0038 - acc: 0.7201 - val_loss: 0.0039 - val_acc: 0.6869
Epoch 17/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0037 - acc: 0.7224Epoch 00016: val_loss improved from 0.00378 to 0.00367, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0037 - acc: 0.7217 - val_loss: 0.0037 - val_acc: 0.6916
Epoch 18/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0037 - acc: 0.7234Epoch 00017: val_loss improved from 0.00367 to 0.00363, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0037 - acc: 0.7227 - val_loss: 0.0036 - val_acc: 0.6916
Epoch 19/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0035 - acc: 0.7283Epoch 00018: val_loss improved from 0.00363 to 0.00346, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0035 - acc: 0.7269 - val_loss: 0.0035 - val_acc: 0.6916
Epoch 20/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0035 - acc: 0.7214Epoch 00019: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0035 - acc: 0.7243 - val_loss: 0.0038 - val_acc: 0.6776
Epoch 21/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7273Epoch 00020: val_loss improved from 0.00346 to 0.00344, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0034 - acc: 0.7305 - val_loss: 0.0034 - val_acc: 0.6729
Epoch 22/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7281Epoch 00021: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0034 - acc: 0.7274 - val_loss: 0.0036 - val_acc: 0.7009
Epoch 23/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7224Epoch 00022: val_loss improved from 0.00344 to 0.00340, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0034 - acc: 0.7222 - val_loss: 0.0034 - val_acc: 0.7009
Epoch 24/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7294Epoch 00023: val_loss improved from 0.00340 to 0.00338, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0034 - acc: 0.7310 - val_loss: 0.0034 - val_acc: 0.7150
Epoch 25/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7274Epoch 00024: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0033 - acc: 0.7279 - val_loss: 0.0034 - val_acc: 0.7150
Epoch 26/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.7316Epoch 00025: val_loss improved from 0.00338 to 0.00319, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0032 - acc: 0.7300 - val_loss: 0.0032 - val_acc: 0.7150
Epoch 27/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7283Epoch 00026: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0034 - acc: 0.7295 - val_loss: 0.0032 - val_acc: 0.7103
Epoch 28/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7222Epoch 00027: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0033 - acc: 0.7222 - val_loss: 0.0037 - val_acc: 0.7009
Epoch 29/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.7305Epoch 00028: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0032 - acc: 0.7300 - val_loss: 0.0033 - val_acc: 0.7103
Epoch 30/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.7347Epoch 00029: val_loss improved from 0.00319 to 0.00306, saving model to weights.best.from_Adam
1926/1926 [==============================] - 1s - loss: 0.0032 - acc: 0.7347 - val_loss: 0.0031 - val_acc: 0.7150
In [255]:
my_training(model_config, 'Adamax')
Train on 1926 samples, validate on 214 samples
Epoch 1/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.2604 - acc: 0.6401Epoch 00000: val_loss improved from inf to 0.08196, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 2s - loss: 0.2553 - acc: 0.6412 - val_loss: 0.0820 - val_acc: 0.6636
Epoch 2/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0489 - acc: 0.7086Epoch 00001: val_loss improved from 0.08196 to 0.02642, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0482 - acc: 0.7103 - val_loss: 0.0264 - val_acc: 0.6589
Epoch 3/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0182 - acc: 0.7086Epoch 00002: val_loss improved from 0.02642 to 0.01245, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0180 - acc: 0.7108 - val_loss: 0.0124 - val_acc: 0.6589
Epoch 4/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0090 - acc: 0.7107Epoch 00003: val_loss improved from 0.01245 to 0.00765, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0090 - acc: 0.7108 - val_loss: 0.0076 - val_acc: 0.6589
Epoch 5/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0060 - acc: 0.7134Epoch 00004: val_loss improved from 0.00765 to 0.00576, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0060 - acc: 0.7103 - val_loss: 0.0058 - val_acc: 0.6589
Epoch 6/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7080Epoch 00005: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0059 - val_acc: 0.6589
Epoch 7/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7091Epoch 00006: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0058 - val_acc: 0.6589
Epoch 8/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0058 - acc: 0.7080Epoch 00007: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0058 - acc: 0.7103 - val_loss: 0.0063 - val_acc: 0.6589
Epoch 9/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0059 - acc: 0.7102Epoch 00008: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0059 - acc: 0.7103 - val_loss: 0.0058 - val_acc: 0.6589
Epoch 10/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0058 - acc: 0.7107Epoch 00009: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0058 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 11/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7096Epoch 00010: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 12/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0058 - acc: 0.7096Epoch 00011: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0058 - acc: 0.7103 - val_loss: 0.0059 - val_acc: 0.6589
Epoch 13/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0058 - acc: 0.7134Epoch 00012: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0058 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 14/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7095Epoch 00013: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 15/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7107Epoch 00014: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 16/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7139Epoch 00015: val_loss did not improve
1926/1926 [==============================] - 2s - loss: 0.0057 - acc: 0.7103 - val_loss: 0.0060 - val_acc: 0.6589
Epoch 17/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7086Epoch 00016: val_loss improved from 0.00576 to 0.00480, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 18/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7150- ETA: 1s Epoch 00017: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 19/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7107Epoch 00018: val_loss improved from 0.00480 to 0.00478, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 20/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7102Epoch 00019: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 21/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7112Epoch 00020: val_loss improved from 0.00478 to 0.00476, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 22/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7086Epoch 00021: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 23/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7139Epoch 00022: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 24/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7109Epoch 00023: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 25/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7123- ETA: 1Epoch 00024: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0049 - val_acc: 0.6589
Epoch 26/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7104Epoch 00025: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 27/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7134Epoch 00026: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 28/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7123Epoch 00027: val_loss improved from 0.00476 to 0.00475, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7103 - val_loss: 0.0048 - val_acc: 0.6589
Epoch 29/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0044 - acc: 0.7099Epoch 00028: val_loss improved from 0.00475 to 0.00468, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0044 - acc: 0.7103 - val_loss: 0.0047 - val_acc: 0.6589
Epoch 30/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7107Epoch 00029: val_loss improved from 0.00468 to 0.00466, saving model to weights.best.from_Adamax
1926/1926 [==============================] - 1s - loss: 0.0044 - acc: 0.7103 - val_loss: 0.0047 - val_acc: 0.6589
In [256]:
my_training(model_config, 'Nadam')
Train on 1926 samples, validate on 214 samples
Epoch 1/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.4632 - acc: 0.3931Epoch 00000: val_loss improved from inf to 0.26423, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.4586 - acc: 0.3951 - val_loss: 0.2642 - val_acc: 0.6682
Epoch 2/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.2369 - acc: 0.5820Epoch 00001: val_loss improved from 0.26423 to 0.21183, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.2365 - acc: 0.5831 - val_loss: 0.2118 - val_acc: 0.6869
Epoch 3/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.1868 - acc: 0.6704Epoch 00002: val_loss improved from 0.21183 to 0.16474, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.1864 - acc: 0.6713 - val_loss: 0.1647 - val_acc: 0.6869
Epoch 4/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.1400 - acc: 0.7116Epoch 00003: val_loss improved from 0.16474 to 0.11680, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.1397 - acc: 0.7103 - val_loss: 0.1168 - val_acc: 0.6729
Epoch 5/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0961 - acc: 0.7218Epoch 00004: val_loss improved from 0.11680 to 0.07576, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 1s - loss: 0.0956 - acc: 0.7222 - val_loss: 0.0758 - val_acc: 0.6636
Epoch 6/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0596 - acc: 0.7230Epoch 00005: val_loss improved from 0.07576 to 0.04384, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0594 - acc: 0.7222 - val_loss: 0.0438 - val_acc: 0.6776
Epoch 7/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.0337 - acc: 0.7270Epoch 00006: val_loss improved from 0.04384 to 0.02660, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0336 - acc: 0.7248 - val_loss: 0.0266 - val_acc: 0.6589
Epoch 8/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0179 - acc: 0.7234Epoch 00007: val_loss improved from 0.02660 to 0.01211, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0179 - acc: 0.7238 - val_loss: 0.0121 - val_acc: 0.6729
Epoch 9/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.0090 - acc: 0.7307Epoch 00008: val_loss improved from 0.01211 to 0.00765, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0089 - acc: 0.7290 - val_loss: 0.0076 - val_acc: 0.6869
Epoch 10/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.7276Epoch 00009: val_loss improved from 0.00765 to 0.00516, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0057 - acc: 0.7279 - val_loss: 0.0052 - val_acc: 0.6869
Epoch 11/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.0050 - acc: 0.7238Epoch 00010: val_loss improved from 0.00516 to 0.00502, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0050 - acc: 0.7227 - val_loss: 0.0050 - val_acc: 0.6916
Epoch 12/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0049 - acc: 0.7221Epoch 00011: val_loss improved from 0.00502 to 0.00487, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0049 - acc: 0.7227 - val_loss: 0.0049 - val_acc: 0.6729
Epoch 13/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0051 - acc: 0.7234Epoch 00012: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0051 - acc: 0.7227 - val_loss: 0.0052 - val_acc: 0.6869
Epoch 14/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0048 - acc: 0.7292Epoch 00013: val_loss improved from 0.00487 to 0.00465, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0048 - acc: 0.7279 - val_loss: 0.0047 - val_acc: 0.6916
Epoch 15/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7282Epoch 00014: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0047 - acc: 0.7269 - val_loss: 0.0067 - val_acc: 0.6916
Epoch 16/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7209Epoch 00015: val_loss improved from 0.00465 to 0.00435, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0046 - acc: 0.7227 - val_loss: 0.0044 - val_acc: 0.6729
Epoch 17/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.7181Epoch 00016: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7217 - val_loss: 0.0045 - val_acc: 0.6729
Epoch 18/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7242Epoch 00017: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7248 - val_loss: 0.0046 - val_acc: 0.7009
Epoch 19/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0046 - acc: 0.7246Epoch 00018: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0046 - acc: 0.7233 - val_loss: 0.0045 - val_acc: 0.6776
Epoch 20/30
1900/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7274Epoch 00019: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0045 - acc: 0.7279 - val_loss: 0.0049 - val_acc: 0.6776
Epoch 21/30
1920/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7328Epoch 00020: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0045 - acc: 0.7316 - val_loss: 0.0050 - val_acc: 0.7103
Epoch 22/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7271Epoch 00021: val_loss improved from 0.00435 to 0.00432, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0045 - acc: 0.7264 - val_loss: 0.0043 - val_acc: 0.7056
Epoch 23/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7257Epoch 00022: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0045 - acc: 0.7274 - val_loss: 0.0046 - val_acc: 0.6776
Epoch 24/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.7321Epoch 00023: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0045 - acc: 0.7321 - val_loss: 0.0043 - val_acc: 0.7103
Epoch 25/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0044 - acc: 0.7394Epoch 00024: val_loss did not improve
1926/1926 [==============================] - 1s - loss: 0.0044 - acc: 0.7357 - val_loss: 0.0045 - val_acc: 0.7150
Epoch 26/30
1870/1926 [============================>.] - ETA: 0s - loss: 0.0044 - acc: 0.7267Epoch 00025: val_loss improved from 0.00432 to 0.00400, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0044 - acc: 0.7279 - val_loss: 0.0040 - val_acc: 0.7056
Epoch 27/30
1890/1926 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.7397Epoch 00026: val_loss did not improve
1926/1926 [==============================] - 2s - loss: 0.0043 - acc: 0.7388 - val_loss: 0.0044 - val_acc: 0.6963
Epoch 28/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.7293Epoch 00027: val_loss did not improve
1926/1926 [==============================] - 2s - loss: 0.0043 - acc: 0.7285 - val_loss: 0.0045 - val_acc: 0.7103
Epoch 29/30
1910/1926 [============================>.] - ETA: 0s - loss: 0.0042 - acc: 0.7335Epoch 00028: val_loss did not improve
1926/1926 [==============================] - 2s - loss: 0.0042 - acc: 0.7342 - val_loss: 0.0044 - val_acc: 0.7009
Epoch 30/30
1880/1926 [============================>.] - ETA: 0s - loss: 0.0042 - acc: 0.7282Epoch 00029: val_loss improved from 0.00400 to 0.00399, saving model to weights.best.from_Nadam
1926/1926 [==============================] - 2s - loss: 0.0042 - acc: 0.7264 - val_loss: 0.0040 - val_acc: 0.7196

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [272]:
# model = load_model('my_model.h5')
model = load_model('weights.best.from_RMSprop')
In [273]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [274]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')


# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image)
Out[274]:
<matplotlib.image.AxesImage at 0x7fc0fe2b6278>
In [275]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
all_faces_gray = []
all_faces = []
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    # cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    # Corp the color face
    face = image[y:y+h, x:x+w]
    all_faces.append(face)
    # Corp the gray face
    face_gray = gray[y:y+h, x:x+w]
    print("face_gray.shape == {}".format(face_gray.shape))
    # Resize the face image to fit the input size of CNN model
    face_resized = cv2.resize(face_gray, (96,96))
    print("face_resized.shape == {}".format(face_resized.shape))
    # Display the detectd face
    fig = plt.figure(figsize = (6,6))
    ax1 = fig.add_subplot(111)
    ax1.set_xticks([])
    ax1.set_yticks([])
    ax1.set_title('Detected faces')
    ax1.imshow(face_resized)
    # Scale pixel values to [0, 1]
    face_resized = face_resized/255
    print(type(face_resized))
    # Append the processed face to all_faces_gray
    all_faces_gray.append(face_resized)

# Create numpy array
all_faces_gray = np.array(all_faces_gray)
# Return each images as 96 x 96 x 1
all_faces_gray = all_faces_gray.reshape(-1, 96, 96, 1)
print("all_faces_gray.shape == {}".format(all_faces_gray.shape))

# Print the keypoints on detected faces
keypoints = model.predict(all_faces_gray)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(2):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(all_faces_gray[i], keypoints[i], ax)
    
Number of faces detected: 2
face_gray.shape == (175, 175)
face_resized.shape == (96, 96)
<class 'numpy.ndarray'>
face_gray.shape == (166, 166)
face_resized.shape == (96, 96)
<class 'numpy.ndarray'>
all_faces_gray.shape == (2, 96, 96, 1)
In [276]:
## TODO : Paint the predicted keypoints on the test image
# Undo the normalization
keypoints = keypoints * 48 + 48 
idx = 0
for (x,y,w,h) in faces:
    keypoint = keypoints[idx]
    # Calculate the scaling to map the keypoint back to original face image
    face_resized = all_faces_gray[idx]
    scaling = h / face_resized.shape[0]
    # Map the keypoint back to original face image
    keypoint = keypoint * scaling
    # Save the keypoint
    keypoints[idx] = keypoint
    # Display keypoints on original face image
    image_copy = np.copy(image)
    face = image_copy[y:y+h, x:x+w]
    i = 0
    while (i < keypoint.size):
        cv2.circle(face, (keypoint[i],keypoint[i+1]), 2, (0,255,0), 2)
        i = i + 2
    image_with_detections[y:y+h, x:x+w] = face
    # Display the face
    fig = plt.figure(figsize = (6,6))
    ax1 = fig.add_subplot(111)
    ax1.set_xticks([])
    ax1.set_yticks([])
    ax1.set_title('Face with keypoint')
    ax1.imshow(face)
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    idx = idx + 1
    
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image_with_detections')
ax1.imshow(image_with_detections)
Out[276]:
<matplotlib.image.AxesImage at 0x7fc0f19afcc0>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [277]:
import cv2
import time 
from keras.models import load_model
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        # plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [278]:
# Run your keypoint face painter
#laptop_camera_go()

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [279]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [280]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [281]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
the alpha channel here looks like
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109]), array([ 687,  688,  689, ..., 2376, 2377, 2378]))

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [282]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[282]:
<matplotlib.image.AxesImage at 0x7fc0fac61eb8>
In [283]:
def blend_transparent(face, sunglasses, y_offset, x_offset):
    l_img = np.copy(face)
    s_img = np.copy(sunglasses)
    
    y1, y2 = y_offset, y_offset + s_img.shape[0]
    x1, x2 = x_offset, x_offset + s_img.shape[1]

    alpha_s = s_img[:, :, 3] / 255.0
    alpha_l = 1.0 - alpha_s

    for c in range(0, 3):
        l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                                  alpha_l * l_img[y1:y2, x1:x2, c])
        
    return l_img
In [284]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

# Add alpha channel in image
b_channel, g_channel, r_channel = cv2.split(image)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255 # creating a 255 alpha channel image.
image = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))

idx = 0
image_with_sunglasses = np.copy(image)
for (x,y,w,h) in faces:
    image_copy = np.copy(image)
    # Get the keypoint of this face
    keypoint = keypoints[idx]
    # Corp the face
    face = image_copy[y:y+h, x:x+w]
    # Get the size of the sunglasses
    sunglasses_height, sunglasses_width = sunglasses.shape[0], sunglasses.shape[1]
    # Get eye keypoint coordinates
    keypoint_7_y, keypoint_7_x = int(round(keypoint[7*2+1])), int(round(keypoint[7*2]))
    keypoint_9_y, keypoint_9_x = int(round(keypoint[9*2+1])), int(round(keypoint[9*2]))
    # Get the width of the eyes = x of 7th - x of 9th
    eye_width = keypoint_7_x - keypoint_9_x
    # Resize sunglasses to fit on the face
    sunglasses_resized = cv2.resize(sunglasses, (eye_width,int(round(eye_width/sunglasses_width*sunglasses_height))))
    # Paint the sunglasses on the face    
    face = blend_transparent(face, sunglasses_resized, keypoint_9_y, keypoint_9_x)
    # Put back to the image_with_sunglasses
    image_with_sunglasses[y:y+h, x:x+w] = face
    
    
# Print the image_with_sunglasses
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image_with_sunglasses')
ax1.imshow(image_with_sunglasses)
Out[284]:
<matplotlib.image.AxesImage at 0x7fc0f138c6a0>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [285]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [286]:
# Load facial landmark detector model
model = load_model('my_model.h5')

# Run sunglasses painter
#laptop_camera_go()